import 'package:faker/utils/route_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as html;
import 'package:http/http.dart' as http;
import 'package:share/share.dart';

/// WebView 加载网页页面
class WebViewWidget extends StatefulWidget {
  /// 标题
  String title;

  /// 链接
  String url;

  WebViewWidget({Key key, @required this.title, @required this.url})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new WebViewWidgetState();
  }
}

class WebViewWidgetState extends State<WebViewWidget> {
  bool isLoad = true;

  String data = "";

  final flutterWebViewPlugin = new FlutterWebviewPlugin();

  @override
  void initState() {
    this.getdata();
    super.initState();
    flutterWebViewPlugin.onStateChanged.listen((state) {
      if (state.type == WebViewState.finishLoad) {
        setState(() {
          isLoad = false;
        });
      } else if (state.type == WebViewState.startLoad) {
        setState(() {
          isLoad = true;
        });
      }
    });
  }

  getdata() async {
    var response = await http.get(widget.url);
    if (response.statusCode == 200) {
      setState(() {
        dom.Document doc = html.parse(response.body);
        String htmlContent = doc.body.innerHtml;
        data = htmlContent;
        print(data);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      url: widget.url,
      appBar: new AppBar(
        backgroundColor: Theme.of(context).backgroundColor,
        elevation: 0.4,
        title: new Text(widget.title),
        bottom: new PreferredSize(
          child: SizedBox(
            height: 2,
            child: isLoad ? new LinearProgressIndicator() : Container(),
          ),
          preferredSize: Size.fromHeight(2),
        ),
        actions: <Widget>[
          IconButton(
            // tooltip: '用浏览器打开',
            icon: Icon(Icons.explore, size: 20.0),
            onPressed: () {
              RouteUtil.launchInBrowser(widget.url, title: widget.title);
            },
          ),
          IconButton(
            // tooltip: '分享',
            icon: Icon(Icons.share, size: 20.0),
            onPressed: () {
              Share.share('${widget.title} : ${widget.url}');
            },
          ),
        ],
      ),
      withZoom: false,
      withLocalStorage: true,
      withJavascript: true,
      hidden: true,
    );
  }

  Widget openInHtml(htmldata) {
    return Html(
      data: htmldata,
      padding: EdgeInsets.all(8.0),
      linkStyle: const TextStyle(
        color: Colors.redAccent,
        decorationColor: Colors.redAccent,
        decoration: TextDecoration.underline,
      ),
      onLinkTap: (url) {
        print("Opening $url...");
      },
      onImageTap: (src) {
        print(src);
      },
      //Must have useRichText set to false for this to work
      customRender: (node, children) {
        if (node is dom.Element) {
          switch (node.localName) {
            case "custom_tag":
              return Column(children: children);
          }
        }
        return null;
      },
      customTextAlign: (dom.Node node) {
        if (node is dom.Element) {
          switch (node.localName) {
            case "p":
              return TextAlign.justify;
          }
        }
        return null;
      },
      customTextStyle: (dom.Node node, TextStyle baseStyle) {
        if (node is dom.Element) {
          switch (node.localName) {
            case "p":
              return baseStyle.merge(TextStyle(height: 2, fontSize: 20));
          }
        }
        return baseStyle;
      },
    );
  }

  @override
  void dispose() {
    flutterWebViewPlugin.dispose();
    super.dispose();
  }
}
